package com.logic.modular.game.battle.process.skillEffectHandle.base;

import cn.hutool.core.util.ObjectUtil;
import com.logic.comment.util.BeanUtil;
import com.logic.modular.game.battle.panel.Battle;
import com.logic.modular.game.battle.panel.attribute.PlayerHeroAttributeServiceImpl;
import com.logic.modular.game.battle.panel.attribute.domain.PlayerHeroAttribute;
import com.logic.modular.game.battle.panel.skillEffect.PvpSkillEffect;
import com.logic.modular.game.battle.panel.skillEffect.PvpSkillEffectServiceImpl;
import com.logic.modular.game.battle.panel.skillEffect.domain.BaseTrigger;
import com.logic.modular.game.battle.panel.skillEffect.domain.LayerValue;
import com.logic.modular.game.battle.panel.skillEffect.domain.SkillEffectStatus;
import com.logic.modular.game.battle.process.domain.Reason;
import com.logic.modular.game.battle.process.skillEffectHandle.skillEffectSelect.SkillEffectTriggerHandle;
import com.logic.modular.game.battle.info.FiledName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.stream.Collectors;

/**
 * 判定
 * 触发|状态(新增|刷新|过期)
 */
@Slf4j
@Component
public class EffectHandle2 {
    @Resource
    private PlayerHeroAttributeServiceImpl attributeService;
    @Resource
    private PvpSkillEffectServiceImpl skillEffectService;

    /**
     * 技能效果-判定
     * 施加|触发
     */
    public void tryTriggerJudgment(PvpSkillEffect skillEffect) {
        Reason reason = new Reason();

        SkillEffectStatus status = skillEffect.getStatus();
        status.setIsTrigger(1);
        if (status.getStatus() == 5) {
            status.setStatus(2);
        }
        String battleUUID = skillEffect.getBattleUUID();
        Long battleId = skillEffect.getBattleId();
        Battle battle = Battle.get(battleUUID);
        Long sourcePlayerHeroId = skillEffect.getSourcePlayerHeroId();
        Long targetPlayerHeroId = skillEffect.getTargetPlayerHeroId();
        Long coreSkillStarId = skillEffect.getSourceCoreSkillStarId();

        PlayerHeroAttribute sourceAttribute = attributeService.get(battleUUID, sourcePlayerHeroId);
        PlayerHeroAttribute targetAttribute = attributeService.get(battleUUID, targetPlayerHeroId);

        BaseTrigger trigger = skillEffect.getBaseTrigger();

        // 判定是否达到最大叠加次数
        Map<Integer, LayerValue> layerValueMap = skillEffect.getSkillEffectLayer().getLayerValueMap();
        Integer maxNum = skillEffect.getBaseEffectValueInfo().getBaseValueMax();
        if (!layerValueMap.isEmpty()) {
            LayerValue layerValue = layerValueMap.get(1);
            if (layerValue.getTriggerCount() >= maxNum) {
                status.setIsTrigger(0);
                status.setStatus(5);
            }
        }

        // 过期判定
        List<Integer> integers = skillEffect.obtainNumberOfEffectiveRounds();
        OptionalInt max = integers.stream().mapToInt(Integer::intValue).max();
        if (max.isPresent()) {
            int maxAsInt = max.getAsInt();
            if (maxAsInt < battle.getRound()) {
                status.setIsTrigger(0);
                status.setStatus(4);
                status.setStatus4Value(maxAsInt);
            }
        } else {
            throw new RuntimeException("未找到最大值");
        }

        // 触发判定1
        Integer trigger1 = trigger.getTrigger1();
        if (trigger1 >= 1) {
            Integer targetAttributeSkillBattleCountNum = targetAttribute.getSkillBattleCount().get(skillEffect.getSourceCoreSkillStarId());
            if (!targetAttributeSkillBattleCountNum.equals(trigger1)) {
                status.setIsTrigger(0);
                status.triggerFailReasons.put(-1, "非战斗的指定数");
            }
        }

        // 触发判定2
        Integer trigger2 = trigger.getTrigger2();
        if (trigger2 >= 1) {
            Integer targetAttributeSkillRoundCountNum =
                    targetAttribute
                            .getSkillRoundCount()
                            .get(skillEffect.getSourceCoreSkillStarId());
            if (ObjectUtil.equals(targetAttributeSkillRoundCountNum, trigger2)) {
                status.setIsTrigger(0);
                status.triggerFailReasons.put(-2, "非触发的回合数");
            }
        }

        // 触发判定3
        Integer trigger3 = trigger.getTrigger3();
        if (trigger3 >= 1) {
            Integer targetAttributePhase = targetAttribute.getPhase();
            if (!targetAttributePhase.equals(trigger3)) {
                status.setIsTrigger(0);
                String res = "非处于" + FiledName.phaseMap.get(trigger3) + "阶段,阶段当前阶段:" + FiledName.phaseMap.get(targetAttributePhase);
                status.triggerFailReasons.put(-3, res);
            }
        }

        // 触发判定4
        List<Integer> trigger4 = trigger.getTrigger4();
        if (!trigger4.isEmpty()) {
            Map<Integer, String> event = targetAttribute.getEvent();
            event.forEach((skillType, value) -> {
                if (!trigger4.contains(skillType)) {
                    status.setIsTrigger(0);
                    String res = "非匹配战法," + skillType + ":" + value;
                    status.triggerFailReasons.put(-5, res);
                }
            });
        }
        // 触发判定5
        List<Long> trigger5 = trigger.getTrigger5();
        if (!trigger5.isEmpty()) {
            for (Long l : trigger5) {
                if (!targetAttribute.behaviorMap.containsKey(l)) {
                    status.setIsTrigger(0);
                    String res = "非匹配行为";
                    status.triggerFailReasons.put(-5, res);
                }
            }
        }

        Integer trigger6 = trigger.getTrigger6();
        // 触发概率判定
        boolean b = trigger.resProbability();
        if (!b) {
            status.setIsTrigger(0);
            String res = -6 + ":概率未通过";
            status.triggerFailReasons.put(-6, res);
        }

        // 触发次数判定
        Integer triggerNum = trigger.getTriggerNum();
        Integer numberOfTriggersThisRound =
                status.getNumberOfTriggersThisRound();
        if (numberOfTriggersThisRound > triggerNum) {
            status.setIsTrigger(0);
            String res = "回合触发最大次数到达上限";
            status.triggerFailReasons.put(-7, res);
        }

        skillEffect.setStatus(status);
    }

    public List<PvpSkillEffect> effectTriggerBy(
            String behaviorName,
            PlayerHeroAttribute sourceAttribute,// 释放技能的来源
            PlayerHeroAttribute targetAttribute // 技能效果目标对象
    ) {
        // log.info("=====================战斗{}行为触发信息========================",behaviorName);
        ArrayList<PvpSkillEffect> triggerList = new ArrayList<>();
        String battleUUID = sourceAttribute.getBattleUUID();
        Battle battle = Battle.get(battleUUID);
        Long battleId = battle.getBattleId();

        Long sourceAttributeId = sourceAttribute.getId();
        Map<String, List<PvpSkillEffect>> collect1 = skillEffectService.list(battleId).stream()
                .filter(item -> new BeanUtil.Selector()
                        .eq(sourceAttribute.getId(), item.getTargetPlayerHeroId())
                        .bool(item.pdTrigger5(sourceAttribute.getBehaviorMap()))
                        .value()
                ).collect(Collectors.groupingBy(p ->
                        "来源武将:" + p.getSourcePlayerHeroId() + "-"
                                + "技能id:" + p.getSourceCoreSkillId() + "-"
                                + "技能星阶id:" + p.getSourceCoreSkillStarId() + "-"
                                + "技能名称:" + p.getCoreSkillName() + "-"
                                + "[技能描述:" + p.getCoreSkillInfo() + "]"
                ));
        if (!collect1.isEmpty()) {
            log.info("释放者的行为{}触发了", behaviorName);
        }
        collect1.forEach((k, v) -> {
            if (!v.isEmpty()) {
                log.info("效果释放武将:{},{}", sourceAttributeId, k);
                List<PvpSkillEffect> pvpSkillEffects = SkillEffectTriggerHandle.applyNewSkillEffect(v);
                triggerList.addAll(pvpSkillEffects);
            }
        });

        Long targetAttributeId = targetAttribute.getId();
        List<PvpSkillEffect> list2 = skillEffectService.list(battleId).stream()
                .filter(item -> new BeanUtil.Selector()
                        .bool(targetAttributeId.equals(item.getTargetPlayerHeroId()) && item.pdTrigger5(targetAttribute.getBehaviorMap()))
                        .value()
                ).collect(Collectors.toList());
        Map<String, List<PvpSkillEffect>> collect2 = list2.stream().collect(Collectors.groupingBy(p ->
                "来源武将:" + p.getSourcePlayerHeroId() + "-"
                        + "技能id:" + p.getSourceCoreSkillId() + "-"
                        + "技能星阶id:" + p.getSourceCoreSkillStarId() + "-"
                        + "技能效果名称:" + p.getCoreSkillEffectTypeName() + "-"
                        + "技能名称:" + p.getCoreSkillName() + "-"
                        + "[技能描述:" + p.getCoreSkillInfo() + "]"
        ));
        collect2.forEach((k, v) -> {
            if (!v.isEmpty()) {
                log.info("效果拥有武将:{},{}", targetAttributeId, k);
                List<PvpSkillEffect> pvpSkillEffects = SkillEffectTriggerHandle.applyNewSkillEffect(v);
                triggerList.addAll(pvpSkillEffects);
            }
        });
        // log.info("=====================战斗行为触发信息: END ========================");
        return triggerList;
    }


    /**
     * 打印失败原因
     */
    public void logTriggerFailReasons(PvpSkillEffect skillEffect) {
        SkillEffectStatus status = skillEffect.getStatus();
        if (status.getIsTrigger() == 0) {
            // log.error(
            //         "----{}-->{}[{}:{}触发失败{},失败原因{}]",
            //         skillEffect.getSourcePlayerHeroId(),
            //         skillEffect.getTargetPlayerHeroId(),
            //         skillEffect.getCoreSkillEffectTypeId(),
            //         skillEffect.getCoreSkillEffectTypeName(),
            //         status.triggerFailReasons,
            //         status.failReasons
            // );
        }
    }
}
